  package com.itheima.stock.service.impl;

import com.itheima.stock.cache.Cache;
import com.itheima.stock.constant.RedisConstants;
import com.itheima.stock.dto.LoginDTO;
import com.itheima.stock.entity.SysUser;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.exception.Exceptions;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.response.ResponseResult;
import com.itheima.stock.service.UserService;
import com.itheima.stock.util.IdWorkers;
import com.itheima.stock.util.RedisKeyUtil;
import com.itheima.stock.vo.CaptchaVO;
import com.itheima.stock.vo.LoginVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zby
 * @created 2024-06-24 20:18
 * @description 用户业务实现类
 */
@Service
public class UserServiceImpl implements UserService {


    private final Cache cache;
    private final IdWorkers idWorkers;
    private final SysUserMapper sysUserMapper;
    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(Cache cache, IdWorkers idWorkers, SysUserMapper sysUserMapper, PasswordEncoder passwordEncoder) {
        this.cache = cache;
        this.idWorkers = idWorkers;
        this.sysUserMapper = sysUserMapper;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public CaptchaVO generateCaptcha() {

        // 1. 使用工具类生成一个随机的4位验证码
        String captcha = RandomStringUtils.randomNumeric(4);
        // 2. 将验证码存入缓存
        // 生成key的后缀
        String keySuffix = idWorkers.nextStrId();
        // 生成key
        String redisKey = RedisKeyUtil.generateKey(RedisConstants.CAPTCHA_PREFIX, keySuffix);
        // 存入缓存，并且设置过期时间
        cache.set(redisKey, captcha, RedisConstants.CAPTCHA_EXPIRE);
        // 3. 数据组装返回
        return CaptchaVO.builder()
                        .code(captcha)
                        .rkey(redisKey)
                        .build();
    }

    @Override
    public LoginVO login(LoginDTO dto) {
        // 1. 请求参数校验
        if (ObjectUtils.isEmpty(dto) ||
                ObjectUtils.isEmpty(dto.getUsername()) ||
                ObjectUtils.isEmpty(dto.getPassword()) ||
                ObjectUtils.isEmpty(dto.getCode()) ||
                ObjectUtils.isEmpty(dto.getRkey())
        ) {
            // 抛出异常提示参数异常
            Exceptions.cast(CodeEnum.DATA_ERROR);
        }
        // 2. 核心业务处理
        // 2.1 获取验证码在redis的key
        String rkey = dto.getRkey();
        // 2.2 获取redis中存储的验证码
        String captchaInRedis = cache.get(rkey);
        //2.3 比较redis中的验证码和前端传递的验证码是否相等
        boolean equals = StringUtils.equals(captchaInRedis, dto.getCode());
        // 不相等
        if (!equals) {
            // 提示验证码错误
            Exceptions.cast(CodeEnum.SYSTEM_VERIFY_CODE_ERROR);
        }
        // 2.4 根据用户名查询用户信息
        SysUser user = sysUserMapper.selectByUsername(dto.getUsername());
        // 2.5 判断用户是否存在
        // 用户不存在
        if (ObjectUtils.isEmpty(user) ||
                !passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            // 提示用户账号或者密码错误
            Exceptions.cast(CodeEnum.SYSTEM_PASSWORD_ERROR);
        }
        // 3. 组装数据返回

        return LoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .phone(user.getPhone())
                .nickName(user.getNickName())
                .build();
    }
}